package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdQualityAnalysisReport;
import com.ccp.dev.qbdms.model.WQbdSoftwareproAnls;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.service.WQbdSoftwareproAnlsService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 软件问题分析 信息操作处理控制器
 * 
 * @author wyl
 * @date 2020-07-06 09:55:37
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "软件问题分析")
@RequestMapping("/qbdms/wQbdSoftwareproAnls")
public class WQbdSoftwareproAnlsController extends SysBaseController{
	@Resource
	private WQbdSoftwareproAnlsService wQbdSoftwareproAnlsService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: wyl
     * @date: 2020-07-06 09:55:37
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到软件问题分析首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        wCustomColumnsService.addCustomCols(request);
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        modelMap.put("currentSystemLevel", BaseUtil.getCurrentSystemLevel());
        return "wQbdSoftwareproAnls/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: wyl
    * @date: 2020-07-06 09:55:37
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询软件问题分析",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        ZhiLiangConst.addQueryFilter(queryFilter);
        //默认按照填报时间倒序排列
        if(queryFilter.get("orderField")==null){
            queryFilter.put("orderField","createtime");
            queryFilter.put("orderSeq","DESC");
        }
        //分页数据
        List<WQbdSoftwareproAnls> pageDatas = wQbdSoftwareproAnlsService.queryList(queryFilter);

        try {
            //密级等填充文字
            ZhiLiangConst.showName(pageDatas);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        ZhiLiangConst.showName(pageDatas);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: wyl
     * @date: 2020-07-06 09:55:37
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到软件问题分析新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        if(id.isEmpty()){
            modelMap.put("dept",ContextUtil.getCurrentOrg().getOrgName());
        }
        return "wQbdSoftwareproAnls/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdSoftwareproAnls 保存的对象
    * @return: java.lang.Object
    * @auther: wyl
    * @date: 2020-07-06 09:55:37
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存软件问题分析数据",detail="<#if isAdd>新增<#else>编辑</#if>软件问题分析数据<#if success>成功<#else>失败</#if>" +
            "<#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdSoftwareproAnls wQbdSoftwareproAnls) {
        String id = wQbdSoftwareproAnls.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdSoftwareproAnls.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdSoftwareproAnls);
            wQbdSoftwareproAnls.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            result = wQbdSoftwareproAnlsService.add(wQbdSoftwareproAnls);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdSoftwareproAnls);
            result = wQbdSoftwareproAnlsService.update(wQbdSoftwareproAnls);
            //记录修改操作日志
            SysAuditThreadLocalHolder.putParamerter("modifyInfo",
                    StructureModifyUtil.getModifyInfo(wQbdSoftwareproAnlsService.getOneById(id),wQbdSoftwareproAnls));
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: wyl
    * @date: 2020-07-06 09:55:37
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到软件问题分析详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        modelMap.put("isClose", RequestUtil.getString(request, "isClose"));
        return "wQbdSoftwareproAnls/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: wyl
    * @date: 2020-07-06 09:55:37
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询软件问题分析的一条数据",detail="根据主键id查询软件问题分析的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdSoftwareproAnls wQbdSoftwareproAnls = wQbdSoftwareproAnlsService.getOneById(id);
        if (null == wQbdSoftwareproAnls) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdSoftwareproAnls);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: wyl
    * @date: 2020-07-06 09:55:37
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除软件问题分析数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdSoftwareproAnls wQbdSoftwareproAnls = wQbdSoftwareproAnlsService.getOneById(key);
            if (!userId.equals(wQbdSoftwareproAnls.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(wQbdSoftwareproAnls.getReportStatus())
                    && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdSoftwareproAnls.getReportStatus())
                    && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdSoftwareproAnls.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待报集团、待上报的数据");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = wQbdSoftwareproAnlsService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到软件问题分析导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdSoftwareproAnls/import";
    }


    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    @Action(description="导入软件问题分析资源文件",detail="导入软件问题分析资源文件<#if success>成功<#else></#if>")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                if("problemcount".equals(fieldName) ) {
                    returnType = new ReturnType();
                    returnType.setNewValue(fieldValue.replace(",",""));
                }
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdSoftwareproAnls.class);
        String msg = map.get("msg").toString();
        List<WQbdSoftwareproAnls> list = (List<WQbdSoftwareproAnls>)map.get("instList");
        if(StringUtil.isEmpty(msg)){
            this.wQbdSoftwareproAnlsService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("dataSource.importXml.success");
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail(msg);
        }
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description="跳转到软件问题分析导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request,ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdSoftwareproAnls.class);
        modelMap.put("tableInfo",jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出软件问题分析数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: wyl
     * @date: 2020-07-06 09:55:37
     */
    @RequestMapping("/exportData")
    @Action(description="导出软件问题分析数据信息",detail="导出软件问题分析数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success",false);
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        ZhiLiangConst.addQueryFilter(queryFilter);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter,id);
        //默认按照填报时间倒序排列
        if(queryFilter.get("orderField")==null){
            queryFilter.put("orderField","createtime");
            queryFilter.put("orderSeq","DESC");
        }

        List<WQbdSoftwareproAnls> wQbdSoftwareproAnlsList = this.wQbdSoftwareproAnlsService.queryAll(queryFilter);
        ZhiLiangConst.showName(wQbdSoftwareproAnlsList);
        if(wQbdSoftwareproAnlsList.isEmpty()){
            wQbdSoftwareproAnlsList.add(new WQbdSoftwareproAnls());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request,response,wQbdSoftwareproAnlsList,dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success",true);
    }

    /**
     * 查询上报的信息
     *
     * @param request
     * @param id
     * @param tableName
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(HttpServletRequest request, @RequestParam("id") String id, @RequestParam("tableName") String tableName) {
        //业务数据
        List<WQbdQualityAnalysisReport> reportList = wQbdSoftwareproAnlsService.reportList(id, tableName);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }
}
